<template>
  <div class="customer-bill-wrap">
    <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="table-list min-fill-page">
      <dataDisplay v-if="clientData" :data-list="dataList" type="oneCell" style="margin-bottom: 20px;" />
      <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
        <FilterInput ref="paramsObj" v-model="paramsObj" :filter-list="filterList" is-show-config show-search-btn class="FilterTool" @handelClick="queryClick" @queryEmpty="queryEmpty" @filterTagStatus="filterTagStatus" />
        <div class="opeator-bar">
          <createBtn v-if="hasRouteAuth('crm:customerBill:add')" text="添加账单" style="margin-right:10px;" @click.native="openAddDialog" />
          <btnGroup
            v-if="hasRouteAuth('crm:customerBill:export')"
            ref="btnGroupRef"
            :list="[
              { label:'导出', auth: hasRouteAuth('crm:customerBill:export'), exportApi: '/admin/customerBill/export', exportName:'客户账单', beforeExport: openExportDialog, type: 'export' }
            ]"
            @beginExport="exportDialogClose"
          />
        </div>
      </div>
      <div>
        <div v-loading="listLoading" style="min-height: 300px">
          <u-table
            v-if="list.items.length"
            ref="tableRef"
            :data="list.items"
            :height="setTableHeight"
            :row-height="rowHeight()"
            :border="true"
            :row-class-name="tableRowClassName"
            beautify-table
            header-drag-style
            use-virtual
            class="fb-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
            highlight-current-row
            @sort-change="sortMethod"
            @select="selectTable"
            @select-all="selectTable">
            <u-table-column
              :fixed="selectFixed"
              align="center"
              type="selection"
              width="50"/>
            <u-table-column align="left" label="账单月份">
              <template slot-scope="scope">
                <div class="button-text" @click="toDetail(scope.row.id)">{{ format(scope.row.billMonth,'YYYY/MM') }}</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="客户名称" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.customerName" is-can-click @handelClick="toCustomerPage(scope.row.customerId)" />
              </template>
            </u-table-column>
            <u-table-column align="right" label="含税金额(元)" prop="amount" sortable="custom" min-width="130">
              <template slot-scope="scope">
                <PriceColumn :real-val="scope.row.amount" :price="scope.row.amount / 100" />
              </template>
            </u-table-column>
            <u-table-column align="right" label="已核销金额(元)" prop="writeOffAmount" sortable="custom" width="140">
              <template slot-scope="scope">
                <PriceColumn :real-val="scope.row.writeOffAmount" :price="scope.row.writeOffAmount / 100" />
              </template>
            </u-table-column>
            <u-table-column align="right" label="欠款金额(元)" prop="owePrice" sortable="custom" min-width="130">
              <template slot-scope="scope">
                <PriceColumn :real-val="scope.row.owePrice" :is-highlight="scope.row.writeOffStatus !== 1" :price="scope.row.owePrice / 100" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="逾期天数" prop="overdueDayNum" sortable="custom" min-width="120">
              <template slot-scope="scope">
                <div v-if="scope.row.overdueDayNum" class="highlight">{{ scope.row.overdueDayNum }}</div>
                <div v-else-if="scope.row.overdueDayNum === 0">无逾期</div>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="right" label="逾期欠款金额(元)" min-width="140">
              <template slot-scope="scope">
                <PriceColumn :real-val="scope.row.overduePrice" :price="scope.row.overduePrice / 100" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="未入账订单" min-width="120">
              <template slot-scope="scope">
                <div v-if="scope.row.offBooksOrderNum || scope.row.offBooksOrderNum === 0" :class="{'highlight':scope.row.offBooksOrderNum}">{{ scope.row.offBooksOrderNum }}</div>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="更新时间" min-width="160">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.updateTime,'YYYY/MM/DD HH:mm')" placement="top-start" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="更新人">
              <template slot-scope="scope">
                <CheckUserInfo v-if="scope.row.updater" :label="scope.row.updater" :user-id="scope.row.updaterId" />
                <div v-else-if="scope.row.updaterId === 0">系统更新</div>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建时间" min-width="160">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.createTime,'YYYY/MM/DD HH:mm')" placement="top-start" />
              </template>
            </u-table-column>
            <u-table-column v-if="hasRouteAuth('crm:customerBill:read') || hasRouteAuth('crm:customerBill:update')" :width="operateWidth" fixed="right" align="left" label="操作">
              <template slot-scope="scope">
                <div class="flex-center">
                  <div v-if="!showMobilePage && hasRouteAuth('crm:customerBill:read')" :class="{'br':hasRouteAuth('crm:customerBill:update')}" class="button-text" @click="toDetail(scope.row.id)">查看</div>
                  <div v-if="!showMobilePage && hasRouteAuth('crm:customerBill:update')" class="button-text" @click="handleUpdate(scope.row.id)">更新</div>
                  <MoreOpeator
                    v-if="showMobilePage"
                    :list="[
                      {
                        label: '查看',
                        auth: hasRouteAuth('crm:customerBill:read'),
                        handelClick: () => {toDetail(scope.row.id)}
                      },{
                        label: '更新',
                        auth: hasRouteAuth('crm:customerBill:update'),
                        handelClick: () => {handleUpdate(scope.row.id)}
                      }
                    ]"
                  >
                    <div v-if="!showMobilePage" slot="button" class="button-text">更多<i class="el-icon-arrow-down"/></div>
                    <el-image v-else slot="button" :src="operateBtns" class="table-dropdown-img"/>
                  </MoreOpeator>
                </div>
              </template>
            </u-table-column>
          </u-table>
          <EmptyPlaceholder v-else-if="!list.isInit" slot="empty" empty-text="暂无数据" mode="table" style="padding-bottom: 0;" />
        </div>
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
          <el-pagination
            v-show="list.total > 0"
            :current-page.sync="page"
            :page-size="perPage"
            :total="list.total"
            :small="true"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="pageLayout"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
          <template v-if="showMobilePage">
            <FilterInput
              ref="FilterToolRef"
              v-model="paramsObj"
              :filter-list="filterList"
              show-search-btn
              show-mobile-icon
              @handelClick="queryClick"
              @queryEmpty="queryEmpty"
              @filterTagStatus="filterTagStatus" />
            <MoreOpeator
              ref="moreOperateRef"
              :list="[
                { label:'导出', refName: 'exportRef', auth: hasRouteAuth('crm:customerBill:export'), exportApi: '/admin/customerBill/export', exportName:'客户账单', isBeforeExport: true, beforeExport: openExportDialog, type: 'export'}
              ]"
              show-mobile-icon
              @beginExport="exportDialogClose"
            />
            <createBtn v-if="hasRouteAuth('crm:customerBill:add')" text="添加账单" style="margin-right:10px;" mobile-table @click.native="openAddDialog" />
          </template>
          <template v-else>
            <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
            <div style="flex: 1;" />
            <el-pagination
              v-show="list.total > 0"
              :current-page.sync="page"
              :page-size="perPage"
              :total="list.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              layout="total, prev, pager, next, sizes, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </template>
        </fixed-pagination>
      </div>
      <addBillDialog ref="addBillTef" :visible="addBillVisible" @afterAddBill="fetchData(true)" @closeDialog="closeDialog" />
      <exportDialog ref="exportBillRef" :visible="exportBillVisible" @close="closeExportDialog" @handleExport="handleExport" />
    </div>
  </div>
</template>

<script>
// components
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import addBillDialog from './components/addBillDialog';
import exportDialog from './components/exportDialog';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import createBtn from '@/components/Common/baseComponent/createBtn';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
// mixins
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
// api
import { getCustomerBillList, updateCustomerBill, customerBillStatistics } from '@/api/customer';
// tools
import { mapState } from 'vuex';
import { showModal } from '@/utils/message';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
import { hasRouteAuth } from '@/utils/permission';
import { format } from '@/filters/date';
// imgs
import icon_16 from '@/assets/dataDisplay/icon_16.png';
import icon_17 from '@/assets/dataDisplay/icon_17.png';
import icon_20 from '@/assets/dataDisplay/icon_20.png';
import icon_21 from '@/assets/dataDisplay/icon_21.png';
export default {
  components: {
    EmptyPlaceholder, addBillDialog, exportDialog,
    dataDisplay, createBtn, btnGroup, MoreOpeator
  },
  mixins: [tableSelections, TableAdaptive, mobileTable],
  data() {
    return {
      icon_16, icon_17, icon_20, icon_21,
      paramsObj: {},
      listLoading: false,
      sortName: '',
      sortType: '',
      clientData: {},
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      page: 1,
      perPage: 20,
      tableRefName: 'tableRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      isUmyTable: true,
      addBillVisible: false,
      exportBillVisible: false
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    tableOutsideHeight() {
      return this.showMobilePage ? 205 : 250;
    },
    dataList() {
      const clientData = this.clientData;
      return [
        { label: '总含税金额', data: clientData['amount'] / 100, icon: icon_16 },
        { label: '已核销金额', data: clientData['writeOffAmount'] / 100, icon: icon_17 },
        { label: '欠款金额', data: clientData['owePrice'] / 100, key: 'oweClientNum', icon: icon_20 },
        { label: '逾期欠款金额', data: clientData['overduePrice'] / 100, icon: icon_21 }
      ];
    },
    filterList() {
      return [
        { keyword: 'customerName', name: '客户名称', type: 'input', labelWidth: '96px' },
        { keyword: 'amount', name: '含税金额', type: 'inputRange', labelWidth: '96px' },
        { keyword: 'writeOffAmount', name: '已核销金额', type: 'inputRange', labelWidth: '96px' },
        { keyword: 'owePrice', name: '欠款金额', type: 'inputRange', labelWidth: '96px' },
        { keyword: 'overdueDayNum', name: '逾期天数', type: 'inputRange', onlyInteger: true, startPlaceholder: '最低数值', endPlaceholder: '最高数值', labelWidth: '96px' },
        { keyword: 'offBooksOrderNum', name: '未入账订单', type: 'inputRange', onlyInteger: true, startPlaceholder: '最低数值', endPlaceholder: '最高数值', labelWidth: '96px' },
        { keyword: 'updater', name: '更新人', type: 'input', labelWidth: '96px' },
        { keyword: 'billMonth', name: '账单月份', timeType: 'monthrange', type: 'rangeDate', labelWidth: '96px', format: 'yyyy/MM', startPlaceholder: '开始时间', endPlaceholder: '结束时间' },
        { keyword: 'updateTime', name: '更新时间', timeType: 'daterange', type: 'rangeDate', labelWidth: '96px', startPlaceholder: '开始时间', endPlaceholder: '结束时间' },
        { keyword: 'createTime', name: '创建时间', timeType: 'daterange', type: 'rangeDate', labelWidth: '96px', startPlaceholder: '开始时间', endPlaceholder: '结束时间' }
      ];
    },
    rangeKeyArr() {
      return [
        { attr: 'amount', start: 'amountStart', end: 'amountEnd', type: 'moneyFixed' },
        { attr: 'writeOffAmount', start: 'writeOffAmountStart', end: 'writeOffAmountEnd', type: 'moneyFixed' },
        { attr: 'owePrice', start: 'owePriceStart', end: 'owePriceEnd', type: 'moneyFixed' },
        { attr: 'overdueDayNum', start: 'overdueDayNumStart', end: 'overdueDayNumEnd', type: 'number' },
        { attr: 'offBooksOrderNum', start: 'offBooksOrderNumStart', end: 'offBooksOrderNumEnd', type: 'number' },
        { attr: 'updateTime', start: 'updateTimeStart', end: 'updateTimeEnd', type: 'time' },
        { attr: 'billMonth', start: 'billMonthStart', end: 'billMonthEnd', type: 'time' },
        { attr: 'createTime', start: 'createTimeStart', end: 'createTimeEnd', type: 'time' }
      ];
    },
    arrayKeyArr() {
      return ['writeOffStatus'];
    }
  },
  activated() {
    const name = this.$route.query.name;
    if (name) this.$set(this.paramsObj, 'customerName', name);
    this.fetchData(true);
  },
  methods: {
    format,
    hasRouteAuth,
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      if (this.clearMixinSelection) this.clearMixinSelection();
      this.queryClick();
    },
    getParams() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      return params;
    },
    getStaticstics(params) {
      customerBillStatistics(params).then(res => {
        if (res.code === 200) {
          this.clientData = res.data;
        }
      }).catch(err => console.error(err.message));
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    exportDialogClose() {
      this.$refs['exportBillRef'].dialogClose();
    },
    closeExportDialog() {
      this.exportBillVisible = false;
    },
    openExportDialog() {
      const data = this.getParams();
      if (this.multipleSelectionAll.length) {
        data.customerBillIds = this.multipleSelectionAll.map(it => it.id).join(',');
      }
      data.exportFrom = 1;
      this.$refs['exportBillRef'].initParams(data);
      this.exportBillVisible = true;
    },
    openAddDialog() {
      this.addBillVisible = true;
    },
    closeDialog() {
      this.addBillVisible = false;
    },
    handleExport(params) {
      this.exportBeforeExport(params);
    },
    exportBeforeExport(params) {
      if (this.$refs.btnGroupRef) {
        this.$refs.btnGroupRef.btnExport(params);
      }
      this.$refs['moreOperateRef'] && this.$refs['moreOperateRef'].btnExport(params, 'exportRef');
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = this.getParams();
      if (this.sortName) params.sortName = this.sortName;
      if (this.sortType) params.sortType = this.sortType;
      this.listLoading = true;
      this.getStaticstics(params);
      params.page = this.page;
      params.perPage = this.perPage;
      getCustomerBillList(params).then(({ data }) => {
        this.list = data;
        this.list.isInit = false;
        this.listLoading = false;
        if (this.setSelectRow) this.setSelectRow(data.items);
      }, result => {
        this.listLoading = false;
      }).catch(e => {
        console.error(e);
      });
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleUpdate(id) {
      showModal('请确定是否更新').then(() => {
        updateCustomerBill(id).then(res => {
          if (res.code === 200) {
            this.$message.success('操作成功');
            this.fetchData();
          }
        });
      });
    },
    toCustomerPage(id) {
      const routeUrl = this.$router.resolve({
        name: 'detailCustomer',
        params: { customerId: id }
      });
      window.open(routeUrl.href, '_blank');
    },
    toDetail(id) {
      this.$router.push({
        name: 'detailCustomerBill',
        params: { id }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.customer-bill-wrap {
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
  }
  .opeator-bar {
    position: absolute;
    right: 0;
    top: 0;
    display: flex;
    align-items: center;
  }
  .highlight {
    color: #FF4E5F;
  }
}
</style>
